import Vue from 'vue'
import VueRouter from "vue-router";
import LoginView from "@/components/LoginView";
import RegisterView from "@/components/RegisterView";
import IndexView from "@/components/IndexView";
import FileNotFoundView from "@/components/FileNotFoundView";

// 扩展路由插件
Vue.use(VueRouter)


// 创建路由列表
const routes = [
    {
        path:'/',
        redirect:"/login"
    },

    {
       path:'/login',
       component:LoginView
    },
    {
        path:'/register',
        component:RegisterView
    },
    {
        path:'/index',
        component:IndexView
    },
    {
        path:'/**',
        component:FileNotFoundView   // 404 页面的配置   该路由需要设置在最后
    }
]

// 创建路由对象
 const router = new VueRouter({
     routes
 })


//路由守卫    to  需要跳转的路径  from  从哪个路径来     next  是否放行

router.beforeEach((to, from, next) => {

    //1. 用户没有登录不能直接访问  /index
    //2.用户已经登录  访问 /login   -> /index
    // 3.login  register  是非受限资源可以直接放行

    let path = to.path;
    console.log("path = "+path)

    let user = sessionStorage.getItem("user");
    console.log("user=>"+user)

    switch (path) {
        case '/login':
            if (user){
                next("/index")
            }else {
                next()
            }
            break;
        case '/register':
            next();
            break;
        default:
            if (user){
                next();
            }else{
                next("/login")
            }
    }


})

// 导出 router
export default router
